# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
# 使用需要安装pillow-pil库
import PIL
from PIL import Image
import os
import sys

from PIL.Image import Resampling

IMAGE_WIDTH = 720
IMAGE_HEIGHT = 1600
IMAGE_FORMAT = ['.JPG', '.jpg']
IMAGE_PATH = "./pic/"

IMAGE_ROW = 2  # 行数
IMAGE_COLUMN = 3  # 列数
if len(sys.argv) >= 2:
    try:
        IMAGE_ROW = int(sys.argv[1])
    except ValueError:
        IMAGE_ROW = 3
if len(sys.argv) >= 3:
    try:
        IMAGE_COLUMN = int(sys.argv[2])
    except ValueError:
        IMAGE_COLUMN = 3

image_names = []
for name in os.listdir(IMAGE_PATH):
    if (os.path.splitext(name)[1] in IMAGE_FORMAT) and (os.path.splitext(name)[0] != 'result'):
        image_names.append(name)


def image_compose():
    if len(image_names) > IMAGE_ROW * IMAGE_COLUMN:
        return
    to_image = Image.new('RGB', (IMAGE_COLUMN * IMAGE_WIDTH, IMAGE_ROW * IMAGE_HEIGHT))
    # 循环遍历后粘贴
    for y in range(1, IMAGE_ROW + 1):
        for x in range(1, IMAGE_COLUMN + 1):
            if (IMAGE_COLUMN * (y - 1) + x - 1) >= len(image_names):
                break
            from_image = Image.open(IMAGE_PATH+image_names[IMAGE_COLUMN * (y - 1) + x - 1]).resize(
                (IMAGE_WIDTH, IMAGE_HEIGHT), Resampling.LANCZOS)
            # 粘贴
            to_image.paste(from_image, ((x - 1) * IMAGE_WIDTH, (y - 1) * IMAGE_HEIGHT))
    # 保存新图
    return to_image.save(IMAGE_PATH+"result.jpg")


def print_hi(name):
    # Use a breakpoint in the code line below to debug your script.
    print(f'Hi, {name}')  # Press Ctrl+F8 to toggle the breakpoint.


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    # print_hi('PyCharm')
    image_compose()

# See PyCharm help at https://www.jetbrains.com/help/pycharm/
